package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;

import java.util.*;

/**
 * 聊天群
 *
 * @author whx
 * @date 2017/08/19
 */
public class ChatGroupController extends Controller {
    public void index() {
        renderJsp("/chatgroup_list.jsp");
    }

    public void pagination() {
        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        List<Object> params = new ArrayList<Object>();
        StringBuilder sqlExceptSql = new StringBuilder(" from user u, chat_group cg where u.id = cg.owner_id");
        String selectSql = "select cg.id, u.nick_name as owner, u.nick_name as administrator, " +
                "cg.name, cg.status, cg.create_time, cg.administrator_id, cg.owner_id";

        String name = getPara("name", "");
        if (StringUtil.isNotEmpty(name.trim())) {
            sqlExceptSql.append( " and cg.name like ?");
            params.add("%" + name.trim() + "%");
        }

        int status = getParaToInt("status", -1);
        if (status != -1) {
            sqlExceptSql.append( " and cg.status = ?");
            params.add(status);
        }

        Page<Record> recordList = Db.paginate(pageNumber, limit, selectSql, sqlExceptSql.toString(), params.toArray());

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    /**
     * 激活
     */
    @Before(Tx.class)
    public void activate() {

        Long id = getParaToLong("id");
        Record chatGroupRecord = Db.findById("chat_group",id);
        chatGroupRecord.set("status", 1);
        if (Db.update("chat_group",chatGroupRecord)) {
            renderJson(new JsonResult().status("000").show("激活成功"));
        }else {
            renderJson(new JsonResult().status("-1").show("激活失败"));
        }
    }

    /**
     * 冻结
     */
    @Before(Tx.class)
    public void freeze() {
        Long id = getParaToLong("id");
        Record chatGroup = Db.findById("chat_group",id);
        chatGroup.set("status", 0);
        if (Db.update("chat_group",chatGroup)) {
            renderJson(new JsonResult().status("000").show("冻结成功"));
        }else {
            renderJson(new JsonResult().status("-1").show("冻结失败"));
        }
    }
}
